package com.grape.rabbitmq.queue.core.work;

import com.grape.rabbitmq.queue.util.MQConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import static com.grape.rabbitmq.queue.core.simple.SimpleConstant.QUEUE_NAME;

/**
 * 描述:工作队列消费者
 * @author: myx
 * @date: 2019-04-30
 * Copyright © 2019-grape. All rights reserved.
 */
public class WorkCustomer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1.获取连接
        Connection newConnection = MQConnectionUtils.newConnection(WorkConstant.VIRTUALHOST_NAME);
        // 2.获取通道
        Channel channel = newConnection.createChannel();
        channel.queueDeclare(WorkConstant.QUEUE_NAME, false, false, false, null);
        // 保证一次只分发一次 限制发送给同一个消费者 不得超过一条消息
        channel.basicQos(1);
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                String msgString = new String(body, "UTF-8");
                System.out.println("消费者获取消息:" + msgString);
                try {
                    //通过修改这里的值运行两次课看见效果(两个消费者不再是均分)
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 手动回执消息
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            }
        };
        // 3.监听队列
        channel.basicConsume(WorkConstant.QUEUE_NAME, false, defaultConsumer);
    }
}
